package com.bodacn.storagescan;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.widget.PullRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;

public class QueryActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = this.getClass().getName();
    private final static int MSG_AllowScan=9000;
    private final static int MSG_ScanBarcodeOver=9001;
    private final static int MSG_Detail =9002;
    TextView txt_titleInv, tv_barcodeCaption,tv_ResultInfo;
    CheckBox chk_sameColor,chk_sameSize;
    LinearLayout liner_title;
    Button btn_Query,btn_Scan;
    ImageButton btn_return;
    EditText edit_Barcode,edt_HouseDeName;
    String serviceUrl="http://192.168.10.12/tvservice";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String curLoginUserNo,curLoginUser,curLoginTime;//操作员所属部门等信息;
    String FormType,Caption,PrBarcode;
    JSONArray detailJSON;
    int pageItemCount=8;
    boolean ScanSign=false;
    ListView list_Order;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query);
        InitView();
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curLoginTime=paramBundle.getString("LoginTime");
        serviceUrl=paramBundle.getString("serviceUrl");
        serviceUrlExt=paramBundle.getString("serviceUrlExt");
        FormType=paramBundle.getString("FormType");
        Caption=paramBundle.getString("Caption");
        //置标题颜色
        txt_titleInv.setText(Caption);

    }


    //判断是否为数字，不然不转
    public static boolean isNumer(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    private void InitView(){
        list_Order=findViewById(R.id.list_Order);
        list_Order.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
        chk_sameColor=findViewById(R.id.chk_sameColor);
        chk_sameSize=findViewById(R.id.chk_sameSize);
        btn_Query=findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_Scan=findViewById(R.id.btn_Scan);
        btn_Scan.setOnClickListener(this);
        tv_ResultInfo=findViewById(R.id.tv_ResultInfo);
        edit_Barcode=findViewById(R.id.edit_Barcode);
        edit_Barcode.setInputType(InputType.TYPE_NULL);
        edit_Barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edit_Barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_Barcode,InputMethodManager.SHOW_FORCED);
            }
        });
        edit_Barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        ScanBarcode(edit_Barcode.getText().toString(),"Barcode");
                        return true;
                    }
                }
                return false;
            }
        });
        edit_Barcode.requestFocus();
        edit_Barcode.requestFocusFromTouch();
        edt_HouseDeName=findViewById(R.id.edt_HouseDeName);
        edt_HouseDeName.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        ScanBarcode(edt_HouseDeName.getText().toString(),"HouseDeName");
                        return true;
                    }
                }
                return false;
            }
        });
        liner_title=findViewById(R.id.liner_title);
        tv_barcodeCaption =findViewById(R.id.tv_barcodeCaption);
        txt_titleInv=findViewById(R.id.txt_titleInv);
        btn_return =findViewById(R.id.btn_return);
        btn_return.setOnClickListener(this);

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View view) {
        hideIM(view);
        switch (view.getId()){
            case R.id.btn_return:
                finish();//关闭当前Activity，返回上一级;
                break;
            case R.id.btn_Scan:
                if ((edit_Barcode.getText()!=null)&&(edit_Barcode.getText().length()>0)) {
                    ScanBarcode(edit_Barcode.getText().toString(),"Barcode");
                } else Toast.makeText(getApplicationContext(),"请先输入条码!",Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_Query:
                if ((edt_HouseDeName.getText()!=null)&&(edt_HouseDeName.getText().length()>0)) {
                    ScanBarcode(edt_HouseDeName.getText().toString(),"HouseDeName");
                } else Toast.makeText(getApplicationContext(),"请先输入库位!",Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
    }

    //登陆校验;
    private void ScanBarcode(String paramBarcode,String paramMode){
        hideIM(edit_Barcode);
        String extTj="";
        //组织WebService地址;
        if (FormType==null) FormType="";
        if (PrBarcode==null) PrBarcode="";
        if (chk_sameColor.isChecked()) extTj=extTj+",@SameColor=1";
        if (chk_sameSize.isChecked()) extTj=extTj+",@SameSize=1";
        String SqlComm="Exec App_QueryBarcode @Barcode='"+paramBarcode+"',@FormType='"+FormType+"',@QueryMode='"+(paramMode)+"',@PrBarcode='"+(PrBarcode)+"',@OperType='QueryBarcode',@UserNo='" + curLoginUserNo+"'"+extTj;
        PrBarcode=paramBarcode;
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            hideIM(edit_Barcode);
            edit_Barcode.selectAll();
            edit_Barcode.requestFocus();
            ScanSign=false;
            switch (msgId) {
                case MSG_Detail:
                    System.out.println("MSG_Detail");
                    if (detailJSON!=null) {
                        //刷新表格
                        DetailGridAdapter detailGridAdapter = new DetailGridAdapter(getApplicationContext());
                        detailGridAdapter.jsonArray = detailJSON;
                        list_Order.setAdapter(detailGridAdapter);
                    }
                    break;
                case MSG_ScanBarcodeOver:
                    System.out.println("MSG_ScanBarcodeOver");
                    if (detailJSON!=null) {
                        //填充屏幕
                        fillScreen(detailJSON.optJSONObject(0));
                        //刷新表格
                        DetailGridAdapter detailGridAdapter = new DetailGridAdapter(getApplicationContext());
                        detailGridAdapter.jsonArray = detailJSON;
                        list_Order.setAdapter(detailGridAdapter);
                    }
                    break;
                case MSG_AllowScan:
                    System.out.println("MSG_AllowScan");
                    ScanSign=false;
                    break;
                default:
                    break;
            }
        }
    };

    private void fillScreen(JSONObject optJSONObject) {
        if (optJSONObject!=null){
            try {
                if (optJSONObject.has("OrderNo")) ((EditText) findViewById(R.id.edt_OrderNo)).setText(optJSONObject.getString("OrderNo"));
                if (optJSONObject.has("HouseDeName")) ((EditText) findViewById(R.id.edt_HouseDeName)).setText(optJSONObject.getString("HouseDeName"));
                if (optJSONObject.has("PO")) ((EditText) findViewById(R.id.edt_PO)).setText(optJSONObject.getString("PO"));
                if (optJSONObject.has("CutNum")) ((TextView) findViewById(R.id.edt_CutNum)).setText(optJSONObject.getString("CutNum"));
                if (optJSONObject.has("InNum")) ((TextView) findViewById(R.id.edt_InNum)).setText(optJSONObject.getString("InNum"));
                if (optJSONObject.has("OutNum")) ((TextView) findViewById(R.id.edt_OutNum)).setText(optJSONObject.getString("OutNum"));
                if (optJSONObject.has("ResultInfo")) ((TextView) findViewById(R.id.tv_ResultInfo)).setText(optJSONObject.getString("ResultInfo"));
                if (optJSONObject.has("ErrInfo") == true) {
                    //MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), R.raw.warn);
                    //mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage(optJSONObject.getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideIM(edit_Barcode);
                                    edit_Barcode.selectAll();
                                    edit_Barcode.requestFocus();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign=true;
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    ScanSign=false;
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType")){
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("QueryBarcode")==true){
                                detailJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_ScanBarcodeOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("QueryDetail")==true){
                                detailJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_Detail;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        }
                    } else{
                        Message msg = new Message();
                        msg.what = MSG_AllowScan;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    ScanSign=false;
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();

    }



    //订单表格适配器;
    public final class DetailGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        private JSONArray jsonArray;

        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return jsonArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_query_item, null, false);
            String tmpValue;
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(parent.getHeight()/pageItemCount)));
            int backcolor=getResources().getColor(R.color.white);
            int fontcolor=getResources().getColor(R.color.text_black);
            if (position%2==1) backcolor=getResources().getColor(R.color.listContentColor);
            try {
                if (jsonArray.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = jsonArray.optJSONObject(position).getString("ConColor");
                    backcolor=GetColorValue(tmpValue);
                }
                if (jsonArray.optJSONObject(position).has("ConFontColor")==true) {
                    tmpValue = jsonArray.optJSONObject(position).getString("ConFontColor");
                    fontcolor=GetColorValue(tmpValue);
                }
                TextView tv = convertView.findViewById(R.id.tv_SerNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("SerNo")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("SerNo"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_HouseDeName);// 显示文字
                if (jsonArray.optJSONObject(position).has("HouseDeName")==true)
                    tv.setText(jsonArray.optJSONObject(position).getString("HouseDeName"));
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_BedNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("BedNo")==true)
                    tv.setText(jsonArray.optJSONObject(position).getString("BedNo"));
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_Color);// 显示文字
                if (jsonArray.optJSONObject(position).has("Color")==true)
                    tv.setText(jsonArray.optJSONObject(position).getString("Color"));
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_Size);// 显示文字
                if (jsonArray.optJSONObject(position).has("Size")==true)
                    tv.setText(jsonArray.optJSONObject(position).getString("Size"));
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_PackNum);// 显示文字
                if (jsonArray.optJSONObject(position).has("PackNum")==true)
                    tv.setText(jsonArray.optJSONObject(position).getString("PackNum"));
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_PieceNum);// 显示文字
                if (jsonArray.optJSONObject(position).has("PieceNum")==true)
                    tv.setText(jsonArray.optJSONObject(position).getString("PieceNum"));
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }

    }



    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }



}
